<template>
	<div id="myCart">
		<div id="myCart-header">
			<p>
				<i class="el-icon-notebook-2" style="color: blue;"></i>
				<strong>我的购物车清单</strong>
			</p>
		</div>
		<br>
		<el-table :data="data.carts" border highlight-selection-row highlight-current-row fit show-overflow-tooltip
			@selection-change="goShopping" style="width: 100%;">

			<el-table-column type="selection" >
				<template v-slot:default="scope">
					
				</template>
			</el-table-column>
			<el-table-column label="商品图">
				<template v-slot:default="scope">
					<img :src="pic(scope.row.book.pic)" alt="scope.row.date.book.name" style="width: 50%;">
				</template>
			</el-table-column>
			<el-table-column prop="book.name" label="商品名称" min-width="150px">
			</el-table-column>
			<el-table-column label="单价/元（人民币）" min-width="58px">
				<template v-slot:default="scope">
					{{ scope.row.price }}￥
				</template>
			</el-table-column>
			<el-table-column label="商品数量">
				<template v-slot:default="scope">
					<el-input-number v-model="scope.row.num" controls-position="right" 
						@change="handleChange" :min="1"></el-input-number>
				</template>
			</el-table-column>
			<el-table-column label="总价格/元（人民币）" min-width="58px">
				<template v-slot:default="scope">
					<span style="color: red;">{{ price(scope.row) }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="150px">
				<template v-slot:default="scope">
					<el-button type="danger" size="small" @click="remove(scope.row.id,scope.$index)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div id="myCart-button">
			<div style="margin-right: 20px;display: flex;">
				<span>总价：{{ total }}￥</span>
			</div>
			<el-button type="danger" size="default" @click="makeInCart">前往下单</el-button>
		</div>
	</div>
</template>

<script setup>
	import {
		computed,
		onMounted,
		reactive
	} from 'vue';
	import api from '@/api';
	import pic from '@/api/pic';
	import {
		ElMessage
	} from 'element-plus';
	import router from '../../router';
	import store from '../../store';

	const data = reactive({
		carts: [],
		shopping: []
	})

	const price = (row) => {
		let p = row.price * row.num
		return p.toFixed(2);
	}

	const goShopping = (val) => {
		for(let i=0;i<val.length;i++){
			let c = val[i]
			if(c.num == 0){
				val.splice(i)
				i--;
			}
		}
		console.dir(val)
		data.shopping = val
		console.dir("shopping", data.shopping)
	}

	const handleChange = (newValue, oldValue) => {
		// 可以在这里添加更新总价等逻辑
		console.log(`商品数量从 ${oldValue} 变为 ${newValue}`);
		
	}

	const remove = (id,index) => {
		api.get(`api/cart/delete/${id}`).then((resp)=>{
			if(resp.data.code == 200){
				data.carts = resp.data.data
				console.dir(data.carts)
			}
		})
	}

	const makeInCart = () => {
		for (let i = 0; i < data.shopping.length; i++) {
			if (data.shopping[i].num > data.shopping[i].book.stock) {
				ElMessage.warning({
					message: `商品${data.shopping[i].book.name}的库存不足，无法下单购买`,
					center: true
				})
				return
			}
		}
		if (data.shopping.length <= 0) {
			ElMessage.warning("请选择下单的商品！")
			return
		}
		store.state.cart = data.shopping;
		router.push("/info/building");
	}

	onMounted(() => {
		store.state.cart = []
		api.get("/api/cart/findAll").then((resp) => {
			let rp = resp.data.data;
			data.carts = rp
		})
	})

	const total = computed(()=> {
		let cont = 0;
		for (let i=0; i < data.shopping.length; i++){
			cont = cont + (data.shopping[i].price * data.shopping[i].num)
		}
		console.log('total',data.shopping)
		return cont.toFixed(2);
	}) 

	// 路由跳转时触发事件
	router.beforeResolve((to, from, next) => {
		if(data.carts.length > 0){
			let post = []
			for(let i=0;i<data.carts.length;i++){	
				let p = {id:data.carts[i].id,num:data.carts[i].num,book:{id:data.carts[i].book.id}}
				post.push(p)
			}
			api.postj('/api/cart/updateNum',post)
		}
		store.state.cart = data.shopping;
		next();
	});

</script>

<style lang="less">
	#myCart {
		height: 87vh;
		padding-top: 10px;
		padding-left: 12%;
		padding-right: 12%;

		#myCart-header {
			text-align: center;
			border-bottom: 2px solid #b3d8ff;
		}

		.cell {
			text-align: center;

			.el-input-number {
				width: 90%;
			}
		}

		#myCart-button {
			border-top: 10px solid #b3d8ff;
			border-bottom: 10px solid #b3d8ff;
			display: flex;
			justify-content: end;
			align-items: center;
			// padding: 20px;
		}
	}
</style>